package com.mydemo.common.utils;

import jakarta.annotation.Resource;
import jakarta.mail.internet.MimeMessage;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;


/**
 * 邮件工具类
 *
 * @author Last_Island
 * @version 1.0
 */
@Component
public class EmailUtils {
    @Resource
    private JavaMailSender mailSender;

    /**
     * 发送文字邮件
     *
     * @param targetMail 接收人
     * @param subject 邮件主题
     * @param message 邮件内容
     */
    public void sendMail(String targetMail, String subject, String message) {
        JavaMailSenderImpl sender = (JavaMailSenderImpl) mailSender;
        MimeMessage msg = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(msg, false);
            // 发件人邮箱和名称
            helper.setFrom(sender.getUsername());
            // 收件人邮箱
            helper.setTo(targetMail);
            // 邮件标题
            helper.setSubject(subject);
            // 邮件正文，第二个参数表示是否是HTML正文
            helper.setText("<strong>" + message + "</strong>！", true);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 发送
        mailSender.send(msg);
    }
}
